package com.chenjim.andsignkeyconvert;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

import java.security.MessageDigest;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getAppSign();
    }

    public String getAppSign() {
        String result = null;
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
            if (packageInfo == null) {
                return null;
            }
            Signature[] signatures = packageInfo.signatures;
            if (signatures == null || signatures.length < 1) {
                return null;
            }
            Signature signature = signatures[0];

            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            //messageDigest = MessageDigest.getInstance("SHA-1");

            //取MD5的值并转String
            byte[] md5Bytes = messageDigest.digest(signature.toByteArray());

            //对生成的16字节数组进行补零操作
            StringBuilder md5 = new StringBuilder(md5Bytes.length * 2);
            for (byte b : md5Bytes) {
                if ((b & 0xFF) < 0x10) {
                    md5.append("0");
                }
                md5.append(Integer.toHexString(b & 0xFF));
            }

            result = md5.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.d("getAppSign", "getAppSign result:" + result);
        return result;
    }
}
